using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Windows.Threading;
using ViewOnCore;
using ViewOnCore.HostContract.Media;
using ViewOnCore.Device;
using ViewOnCore.HostContract.Tasks;
using ViewOnCore.Helper.Debug;
using ViewOnCore.Helper.Collection;
using ViewOnCore.Helper.WPF;
using ViewOnCore.HostContract;
using ViewOnCore.Helper.Security;
using MyLibraryDeviceAddIn.Import;

#region Copyright (c) 2006, 2007, 2008 ViewOn Media Services. All rights reserved.

/*
 Copyright (c) 2006, 2007, 2008 ViewOn Media Services. All rights reserved.
 This work is copyrighted in its entirety. Permission to use "ViewOn.tv"
 material may be granted only after we receive a written request from you,
 and you receive written permission from us.

 While ViewOn Media Services provides the information herein to anyone,
 we retain copyright on all code, text, graphic images, and other content.
 This means that you may not distribute the code, the text or graphics to others without the
 express written permission of ViewOn Media Services; "mirror" this information on your server
 without our permission; or modify or reuse the code, text or graphics on our servers.
 You may print copies of the information for your own personal use; and, you may reference
 the Service from your own documents. Any commercial use of this material is prohibited without
 the written permission of ViewOn Media Services. In all copies of this information, you must
 retain this notice and any other copyright notices originally included with such information.

 This material may be protected by U.S. and International Copyright laws, and you are legally
 bound by the copyright notices on those systems.

 "ViewOn" logos and other official symbols or graphics may not be used in connection with any
 product or service that has not been expressly authorized in advance in writing or in any manner
 that is likely to cause confusion among the users of this or other Web sites or among the public.
 All other seals, graphics or trademarks of organizations not affiliated with ViewOn Media Services
 that appear on this site are the property of their respective owners.

 ViewOn Media Services reserve all other rights. 
*/

#endregion

#region ViewOn.tv Source Code Licence

/*
This license governs use of the ViewOn.tv software. If you use the software, you accept this license. If you do not accept the license, do not use the software.

1. Summary

The source code is made available to view for reference purposes or to contribute to the project only. Developers may not distribute or modify the code for commercial or non-commercial purposes without express Agreement of View On Media Services.

2. Definitions

The terms "reproduce," "reproduction," and "distribution" have the same meaning here as under U.S. copyright law.
"Licensor" means the company "ViewOn Media Services".
"You" means the licensee of the software, who is not engaged in designing, developing, or testing other software, that has the same or substantially the same features or functionality as the software.
"Your company" means the company you worked for when you downloaded the software.
"Reference use" means use of the software within your company as a reference, in read only form, for the sole purposes of debugging and maintaining your products. For clarity, "reference use" does NOT include (a) the right to use the software for purposes of designing, developing, or testing other software, that has the same or substantially the same features or functionality as the software, and (b) the right to distribute the software outside of your company.
"Licensed patents" means any Licensor patent claims which read directly on the software as distributed by the Licensor under this license.

3. Grant of Rights

(A) Copyright Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free copyright license to reproduce the software for reference use.
(B) Patent Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free patent license under licensed patents for reference use.
4. Limitations
(A) No Trademark License- This license does not grant you any rights to use the Licensor's name, logo, or trademarks.
(B) If you begin patent litigation against the Licensor over patents that you think may apply to the software (including a cross-claim or counterclaim in a lawsuit), your license to the software ends automatically.
(C) The software is licensed "as-is." You bear the risk of using it. The Licensor gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the Licensor excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 */

#endregion

namespace MyLibraryDeviceAddIn
{
	sealed public class MyLibraryMediaDeviceMusicFeature : MediaFeature
	{

		#region Variables

		//---- db
		private object _dbLock = new object();
		private string _dbFileName = "ud.vod";
		internal XmlDocument XmlDatabase;
        private XmlEncrypter _xmlEncrypter = Host.CreateEncrypter();
		private XmlCustomContext _context;

		#endregion

		#region Constructor

		public MyLibraryMediaDeviceMusicFeature(MyLibraryMediaDevice device)
			: base(new Uri("pack://application:,,,/_images/devicefeature_music.png"), device)
		{
            MediaTypeTags.Add("Music");
		}

		#endregion

		#region Properties

		public override bool IsTagUpdateSupported
		{
			get
			{
				return true;
			}
		}

		override public bool HasMediaItems
		{
			get
			{
				return true;
			}
		}

		#endregion

		#region Is...

        override public string Handle
        {
            get
            {
                return "Music";
            }
        }

		override public bool IsImportSupported
		{
			get
			{
				return true;
			}
		}

		override public bool IsRepeatSupported
		{
			get
			{
				return true;
			}
		}

		override public bool IsShuffleSupported
		{
			get
			{
				return true;
			}
		}

		override public bool IsRemoveSupported
		{
			get
			{
				return true;
			}
		}

        override public bool IsNextPreviousSupported
        {
            get
            {
                return true;
            }
        }

		override public bool IsBurningSupported
		{
			get
			{
				return true;
			}
		}

        override public bool IsManageFilePathSupported
        {
            get
            {
                return true;
            }
        }

		#endregion

		#region OnLoadMediaItems

		override public void OnLoadMediaItems()
		{
			_mediaItems = new List<MediaItem>();

			//---- Load the play lists
            foreach (string fileName in Directory.GetFiles(Host.SettingsService.CachePath, "*.m3u"))
			{
				string name = new FileInfo(fileName).Name.Substring(0, new FileInfo(fileName).Name.Length - 4);
                _mediaItems.Add(new M3UPlayList(this, name));
			}

			//---- Sort
			Comparison<MediaItem> comparison = new Comparison<MediaItem>(
						delegate(MediaItem left, MediaItem right)
						{
							return left.Handle.CompareTo(right.Handle);
						}
						);

            _mediaItems.Sort(comparison);
		}

		#endregion

        #region OnLoadMediaDatas

        public override void OnLoadMediaDatas()
		{
			//---- Load
            XmlDatabase = _xmlEncrypter.LoadEncryptedXML(Host.SettingsService.CachePath + _dbFileName);

			//---- Create the empty Db
			if (XmlDatabase == null)
			{
				XmlDatabase = new XmlDocument();
				XmlDatabase.LoadXml("<db></db>");
                _xmlEncrypter.SaveEncryptedXML(XmlDatabase, Host.SettingsService.CachePath + _dbFileName);
				return;
			}

			//---- Add a Context for extended XPath functions
			_context = new XmlCustomContext((NameTable)XmlDatabase.NameTable);
			_context.AddNamespace("ext", "http://www.ViewOn.tv/");

			//---- Scan file
			XmlNodeList nodes = XmlDatabase.SelectNodes("/db/Music");
			foreach (XmlNode node in nodes)
			{
				Music music = new Music();
                music.FromXml(node);

				_mediaDatas.Add(music);
			}
		}

		#endregion

		#region SaveChanges

		override public void OnSaveChanges()
		{
            _xmlEncrypter.SaveEncryptedXML(XmlDatabase, Host.SettingsService.CachePath + _dbFileName);
		}

		#endregion

		#region CanImport

        public override bool CanImport(MediaFolder parentFolder, object objectToImport)
		{
			MediaData mediaData = objectToImport as Music;

			if (mediaData == null)
				return false;

			return !_mediaDatas.Exists(delegate(MediaData findMediaData)
				{
					return (findMediaData.Path == mediaData.Path);
				});
		}

		#endregion

		#region GetImportDirectoryTask

        override public Task GetImportDirectoryTask(MediaFolder parentFolder, string path)
		{
            return new MyLibraryDeviceAddIn.Import.MyLibraryImportMusic(this, path);
		}

		#endregion

        #region AddMediaData

        override public void AddMediaData(MediaFolder parentFolder, MediaData media, bool saveChanges)
        {
            Music music = (Music)media;

            //---- Update Xml
            XmlNode dbNode = XmlDatabase.SelectSingleNode("/db");

            XmlNode newNode = music.ToXml(XmlDatabase);
            dbNode.AppendChild(newNode);

            //---- Add in the dispatch thread
            Host.ApplicationWindow.Dispatcher.Invoke(DispatcherPriority.Send,
                (DelegateInvoker)delegate
                {
                    MediaDatas.Add(music);
                });

            //---- Save the changes
            if (saveChanges)
            {
                OnSaveChanges();
                Host.MediaService.NotifyMediaDataOperation(this, null, MediaOperationKind.Added, null);
            }
        }

        #endregion

        #region RemoveMediaDatas

        public override void RemoveMediaDatas(MediaFolder parentFolder, List<MediaData> mediaDatas)
		{
            //---- Remove from feature
			foreach (Music music in mediaDatas)
			{
				// Update XML
				XmlNode musicNode = XmlDatabase.SelectSingleNode("/db/Music[@Path='" + XmlConvert.EncodeLocalName(music.Path) + "']");
				musicNode.ParentNode.RemoveChild(musicNode);

				// Remove from the list
				_mediaDatas.Remove(music);
			}

            //---- Remove from the play lists
            foreach (M3UPlayList playlist in MediaItems)
                playlist.RemoveMediaDatas(mediaDatas);

			//---- Save
			OnSaveChanges();
		}

		#endregion

		#region CanUpdateTag

		public override bool CanUpdateTag(MediaData mediaData)
		{
			if (mediaData.Path.ToLower().Trim().EndsWith("m4a"))
				return false;

			return true;
		}

		#endregion

		#region UpdateTag

		public override void UpdateTag(List<MediaData> mediaDatas, MediaDataTagField field, object newValue)
		{
			base.UpdateTag(mediaDatas, field, newValue);

			foreach (MediaData mediaData in mediaDatas)
				UpdateTag(mediaData, field, newValue);
		}

		private void UpdateTag(MediaData mediaData, MediaDataTagField field, object newValue)
		{
			Music music = mediaData as Music;

			if (!File.Exists(music.Path))
				return;

			//---- Update music
			if (field == MediaDataTagField.Title)
				music.Title = newValue.ToString();
			else if (field == MediaDataTagField.Artist)
				music.Artist = newValue.ToString();
			else if (field == MediaDataTagField.Genre)
				music.Genre = newValue.ToString();
			else if (field == MediaDataTagField.Album)
				music.Album = newValue.ToString();
			else if (field == MediaDataTagField.Composer)
				music.Composer = newValue.ToString();
			else if (field == MediaDataTagField.Comment)
				music.Comment = newValue.ToString();
			else if (field == MediaDataTagField.Rating)
				music.Rating = Int32.Parse(newValue.ToString());
			else if (field == MediaDataTagField.Track)
				music.Track = Int32.Parse(newValue.ToString());
			else if (field == MediaDataTagField.TrackCount)
				music.TrackCount = Int32.Parse(newValue.ToString());
			else if (field == MediaDataTagField.Year)
				music.Year = Int32.Parse(newValue.ToString());

			//---- Update the XML
			try
			{
				string xmlPath = XmlConvert.EncodeLocalName(music.Path);
				XmlNode node = XmlDatabase.SelectSingleNode("/db/Music[@Path='" + xmlPath + "']");

				node.Attributes["Title"].Value = XmlConvert.EncodeLocalName(music.Title);
				node.Attributes["Artist"].Value = XmlConvert.EncodeLocalName(music.Artist);
				node.Attributes["Genre"].Value = XmlConvert.EncodeLocalName(music.Genre);
				node.Attributes["Album"].Value = XmlConvert.EncodeLocalName(music.Album);
				node.Attributes["Rating"].Value = music.Rating.ToString();
				node.Attributes["Composer"].Value = XmlConvert.EncodeLocalName(music.Composer);
				node.Attributes["Comment"].Value = XmlConvert.EncodeLocalName(music.Comment);
				node.Attributes["Track"].Value = music.Track.ToString();
				node.Attributes["TrackCount"].Value = music.TrackCount.ToString();
				node.Attributes["Duration"].Value = XmlConvert.EncodeLocalName(music.Duration.ToString());
				node.Attributes["Year"].Value = music.Year.ToString();

				OnSaveChanges();
			}
			catch (Exception e)
			{
				LogManager.Handle(e);
			}

			//---- Update the tag in the file
			try
			{
				music.ToTagLibFile().Save();
			}
			catch (Exception e)
			{
				LogManager.Handle(e);
			}
		}

		#endregion

		#region MediaDeviceItem management

		override public void RemoveMediaItem(MediaItem item)
		{
			try
			{
                File.Delete(((M3UPlayList)item).FilePath);
			}
			catch { }

            //---- Notify
            Host.MediaService.NotifyMediaItemOperation(this, MediaOperationKind.Removed, item);
		}

		override public MediaItem CreateNewMediaItem()
		{
			//---- Create a default name
			int id = 0;
			string name = "noname_" + id;

            string filePath = Host.SettingsService.CachePath + name + ".mu3";
			while (File.Exists(filePath))
			{
				id++;
				name = "noname_" + id;
                filePath = Host.SettingsService.CachePath + name + ".mu3";
			}

			//----
			M3UPlayList playList = new M3UPlayList(this, name);
			MediaItems.Add(playList);
			playList.OnSaveChanges();

            //---- Notify
            Host.MediaService.NotifyMediaItemOperation(this, MediaOperationKind.Added, playList);

			return playList;
		}

		#endregion

	}
}
